package cn.cvs.controller;


import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.service.SysUserService;

import cn.cvs.utils.Constants;
import cn.cvs.utils.Page;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.io.FilenameUtils;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger logger=Logger.getLogger(SysUserController.class);
    List<SysRole> roleList;

    public SysUserController() {

    }
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    //跳转到登录的页面
    @RequestMapping(value = "/toLogin")
    public String login()
    {
        System.out.println("跳转到登录页面");
        return "login";
    }

    //点击退出的时候清楚session
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(Constants.USER_SESSION);
        return "login";
    }

    //执行登录
    @PostMapping("/login")
    public String doLogin(@RequestParam String account, @RequestParam String password, HttpServletRequest request, HttpSession session) throws Exception
    {
        System.out.println("登录方法");

        SysUser sysUser=sysUserService.login(account,password);
        if (null!=sysUser)
        {
            //登录成功,重定向到user/tomain接口
            session.setAttribute(Constants.USER_SESSION,sysUser);
            return "redirect:/user/toMain";
        }else
        {
            //用户不存在,登录失败,跳转到登录页面
            request.setAttribute("error","用户名或密码不正确，请重新输入");
            return "login";
        }
    }


    //跳首页
    @RequestMapping("/toMain")
    public String toMain(HttpSession session) {
        if (session.getAttribute(Constants.USER_SESSION)==null)
        {
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    //异常
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest req)
    {
        req.setAttribute("e",e);
        return "error";
    }

    //一个抛出异常的接口
    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account,@RequestParam String password) throws Exception {
        SysUser user=sysUserService.login(account, password);
        if (null == user )
        {
            throw  new RuntimeException("用户名或者密码不正确");
        }
        return "redirect:/user/toMain";
    }

    @RequestMapping(value = "/toSysError")
    public String sysError()
    {
        return "sysError";
    }



    @RequestMapping("list")
    public String toUserList(Model model
            , @RequestParam(required = false) String queryRealName
            , @RequestParam(required = false) String queryRoleId
            , @RequestParam(defaultValue = "1") Integer pageIndex
    ){
        try
        {
            List<SysUser> userList = null;
            byte pageSize = 5;
            PageHelper.startPage(pageIndex,5);
            userList = this.sysUserService.getUserList(queryRealName, queryRoleId);
            PageInfo<SysUser> pageInfo=new PageInfo<>(userList);
            List<SysRole> roleList = null;
            roleList = this.sysRoleService.getRoleList();
            model.addAttribute("roleList", roleList);
            model.addAttribute("queryRealName", queryRealName);
            model.addAttribute("queryRoleId", queryRoleId);
            model.addAttribute("page",pageInfo);
            return "sysUser/list";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/user/toSysError";
        }
    }

    //跳转到添加用户页面
    @GetMapping({"/toAdd"})
    public String addUser() {
        return "sysUser/add";
    }

    @PostMapping("/add")
    public String addUserSave(SysUser sysUser, HttpSession session, HttpServletRequest request,
                              @RequestParam(value = "attachs",required = false) MultipartFile[] attachs) throws Exception
    {
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        System.out.println("文件路径: ============== > " + path);
        for (int i = 0; i < attachs.length; i++)
        {
            MultipartFile attach = attachs[i];//取到单个文件
            if (!attach.isEmpty())
            {
                if (i == 0)
                {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadFileError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                System.out.println("原文件名:" + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);
                System.out.println("后缀:" + prefix);
                int filesize = 500000;
                System.out.println("文件大小>>>>>" + filesize);
                if (attach.getSize() > filesize) //上传大小不得超过500kb
                {
                    request.setAttribute(errorInfo, "*上传大小不得超过500kb");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pnge")) {
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    System.out.println("新的文件名:" + fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try
                    {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, "* 上传失败");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    System.out.println(">>>>>>>>idPicPath" + idPicPath);
                    System.out.println(">>>>>>>>workPicPath" + workPicPath);
                }
                else
                {
                    request.setAttribute(errorInfo, "* 上传图片格式不正确");
                    flag = false;
                }
            }
        }


        if (flag)
        {
            sysUser.setCreatedUserId(((SysUser) session.getAttribute("userSession")).getId());
            sysUser.setIdPicPath(idPicPath);
            sysUser.setWorkPicPath(workPicPath);
            int count=sysUserService.add(sysUser);
            if (count>0) {
                return "redirect:/user/list";
            }
        }
        return "sysUser/add";
    }



    @GetMapping({"/view/{id}"})
    public String view(@PathVariable Integer id, Model model) throws Exception {
        this.logger.debug("根据id查询用户详情" + id);
        SysUser sysUser = this.sysUserService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }

    @ResponseBody
    @GetMapping({"/{id}/view"})
    public Object view(@PathVariable Integer id) throws Exception {
        this.logger.debug("根据id查询用户详情id:" + id);
        SysUser sysUser = null;
        sysUser = this.sysUserService.getUserById(id);
        this.logger.debug("查询到用户信息：" + sysUser);
        return sysUser;
    }


    @RequestMapping({"/toUpdate"})
    public String getUserById(@RequestParam Integer uid, Model model) throws Exception {
        this.logger.debug("跳转到修改用户信息页面");
        SysUser sysUser = this.sysUserService.getUserById(uid);
        model.addAttribute(sysUser);
        System.out.println("跳转到修改用户信息页面"+sysUser);
        return "sysUser/update";
    }

    @PostMapping({"/update"})
    public String modifyUserSave(SysUser sysUser, HttpSession session) throws Exception {
        this.logger.debug("修改用户信息");
        sysUser.setUpdatedUserId(((SysUser)session.getAttribute("userSession")).getId());
        return this.sysUserService.update(sysUser) ? "redirect:/user/list" : "sysUser/update";

    }

    @DeleteMapping({"/del/{id}"})
    @ResponseBody  //  作用：将方法的返回值，以特定的格式写入到response的body区域，进而将数据返回给客户端。
    public Object del(@PathVariable(value = "id",required = false) Integer id) throws Exception //PathVariable获取URL中路径的参数值
    {
        HashMap resultMap = new HashMap();
        int count=sysUserService.deleteById(id);
        try {
            if (count>0) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        return JSONArray.toJSONString(resultMap);
    }
    @ResponseBody
    @GetMapping({"/userExist"})
    public Object userExist(@RequestParam(required = true) String account) throws Exception {
        this.logger.debug("验证用户名account=" + account + "的用户是否存在");
        HashMap resultMap = new HashMap();

        try {
            if (account != null && !"".equals(account.trim())) {
                SysUser sysUser = this.sysUserService.getByAccount(account);
                if (null != sysUser) {
                    resultMap.put("exist", 1);
                } else {

                    resultMap.put("exist", 0);
                }
            } else {
                resultMap.put("exist", -1);
                resultMap.put("msg", "用户名不可以为空");
            }
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        return JSONArray.toJSONString(resultMap);
    }


    @GetMapping({"/toUpdatePwd"})
    public String toUpdatePwd(HttpSession session) throws Exception {
        return session.getAttribute(Constants.USER_SESSION) == null ? "redirect:/user/toLogin" : "sysUser/updatePassword";
    }

    @ResponseBody
    @PostMapping({"/checkOldPwd"})
    public Object checkOldPwd(@RequestParam String oldPassword, HttpSession session) throws Exception {
        this.logger.debug("验证原密码 oldPassword ===================== " + oldPassword);
        HashMap resultMap = new HashMap();
        try {
            if (null == session.getAttribute("userSession")) {
                resultMap.put("result", "sessionerror");
            } else if (StringUtils.isNullOrEmpty(oldPassword)) {
                resultMap.put("result", "error");
            } else {
                String sessionPwd = ((SysUser)session.getAttribute("userSession")).getPassword();
                if (oldPassword.equals(sessionPwd)) {
                    resultMap.put("result", "true");
                } else {
                    resultMap.put("result", "false");
                }
            }
        } catch (Exception var5) {
            var5.printStackTrace();
        }
        return JSONArray.toJSONString(resultMap);
    }

    @PostMapping({"/savePassword"})
    public String savePassword(@RequestParam("newpassword") String newpassword, HttpSession session, HttpServletRequest request) throws Exception {
        boolean flag = false;
        SysUser loginUser = (SysUser)session.getAttribute("userSession");
        if (loginUser != null && !StringUtils.isNullOrEmpty(newpassword)) {
            flag = this.sysUserService.updatePwd(loginUser.getId(), newpassword);
            if (flag) {
                request.setAttribute("message", "修改密码成功,请退出并使用新密码重新登录！");
                session.removeAttribute("userSession");
                return "login";
            }
            request.setAttribute("message", "修改密码失败！");
        } else {
            request.setAttribute("message", "修改密码失败！");
        }

        return "sysUser/updatePassword";
    }
}
